<template>
  <div class="app-container">
    <!-- 条件栏 -->
    <page-filter
      v-model:query="state.filterInfo.query"
      :filter-list="state.filterInfo.list"
    >
      <template v-slot:filter-deleteItem>
        <el-button
          @click="batchDelete"
          :disabled="formTableInfo.data.length > select.row.length + 1"
          >删除</el-button
        >
      </template>
    </page-filter>

    <!-- 表格 -->
    <table-container
      :refresh="state.tableInfo.refresh"
      :init-curpage="state.tableInfo.initCurpage"
      v-model:data="state.tableInfo.data"
      :api="state.getOrderSequencePage"
      :query="state.filterInfo.query"
      :field-list="state.tableInfo.fieldList"
      :handle="state.tableInfo.handle"
      :check-box="false"
      :tab-index="true"
      @handleEvent="handleEvent"
    ></table-container>
    <!-- 新增修改弹窗 -->
    <page-dialog
      v-if="state.dialogInfo.visible"
      :title="state.dialogInfo.title[state.dialogInfo.type]"
      v-model:visible="state.dialogInfo.visible"
      :width="state.dialogInfo.width"
      :bt-loading="state.dialogInfo.btLoading"
      :bt-list="state.dialogInfo.btList"
    >
      <!-- form -->
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="state.formInfo.ref"
        :data="state.formInfo.data"
        :field-list="state.formInfo.fieldList"
        :rules="state.formInfo.rules"
        :list-type-info="listTypeInfo"
        :label-width="state.formInfo.labelWidth"
      />
      <el-form
        ref="tableForm"
        class="sequence-table-form"
        :model="state.formTableInfo"
        :rules="state.formTableInfo.rules"
        style="width: 100%"
      >
        <page-filter
          v-model:query="state.formFilterInfo.query"
          :filter-list="state.formFilterInfo.list"
        />
        <dialog-table
          v-model:data="state.formTableInfo.data"
          :field-list="state.formTableInfo.fieldList"
          :handle="state.formTableInfo.handle"
          :pager="false"
          @handleEvent="handleEvent"
        >
          <template v-slot:col-currentOrder="scope">
            <el-input
              v-model="scope.row.currentOrder"
              :disabled="true"
            ></el-input>
          </template>
          <template v-slot:col-originNumber="scope">
            <div :class="errorClass">
              <el-form-item
                :prop="'data.' + scope.$index + '.originNumber'"
                :rules="
                  scope.$index >= 0
                    ? state.formTableInfo.rules.originNumber
                    : []
                "
              >
                <el-input-number
                  v-model="scope.row.originNumber"
                  :disabled="scope.row.id && true"
                  controls-position="right"
                  :min="0"
                  :max="100000000"
                  oninput="value=value.replace(/[^\d]/g,'')"
                ></el-input-number>
              </el-form-item>
            </div>
          </template>
          <template v-slot:col-length="scope">
            <div :class="errorClass">
              <el-form-item
                :prop="'data.' + scope.$index + '.length'"
                :rules="
                  scope.$index >= 0 ? state.formTableInfo.rules.length : []
                "
              >
                <el-input-number
                  v-model="scope.row.length"
                  controls-position="right"
                  :min="1"
                  :max="10000"
                  @change="changeItemLength(scope.row)"
                  oninput="value=value.replace(/^0|[^1-9\d]/g, '')"
                ></el-input-number>
              </el-form-item>
            </div>
          </template>
          <template v-slot:col-resetCycle="scope">
            <template v-if="scope.row.type == 2">
              <el-form-item :prop="'data.' + scope.$index + '.resetCycle'">
                <select-model
                  v-model="scope.row.resetCycle"
                  :onlyShowOption="handleValidityUnit(scope.row)"
                  type-code="validity_unit"
                >
                </select-model>
              </el-form-item>
            </template>
            <span v-else>-</span>
          </template>
          <template v-slot:col-type="scope">
            <el-form-item :prop="'data.' + scope.$index + '.type'">
              <select-model v-model="scope.row.type" type-code="order_rule">
              </select-model>
            </el-form-item>
          </template>
          <template v-slot:col-format="scope">
            <template v-if="scope.row.type == 2">
              <el-form-item :prop="'data.' + scope.$index + '.format'">
                <select-model
                  v-model="scope.row.format"
                  type-code="date_format"
                  @change="
                    (str) => {
                      change(str, scope.row)
                    }
                  "
                >
                </select-model>
              </el-form-item>
            </template>
            <span v-else>-</span>
          </template>
          <template v-slot:col-isEnable="scope">
            <el-switch
              v-model="scope.row.isEnable"
              active-text="启用"
              inactive-text="停用"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeSwitch(scope.row.isEnable, scope.$index)"
            >
            </el-switch>
          </template>
        </dialog-table>
      </el-form>
    </page-dialog>
  </div>
</template>

<script setup>
import PageFilter from '@/components/PageFilter/index'
import TableContainer from '@/components/TableContainer/index'
import {
  getOrderSequencePage,
  createOrderSequencePage,
  updateOrderSequencePage,
  getOrderSequenceDetail,
  getMenusPcList,
} from '@/api/base.js'
import PageForm from '@/components/PageForm/index'
import PageDialog from '@/components/PageDialog/index'
import _ from 'lodash'
const { proxy } = getCurrentInstance()
onMounted(() => {
  //getList()
  initRules()
  getMenusList()
})
const listTypeInfo = ref({
  menuList: [],
})
function getMenusList() {
  //获取菜单
  getMenusPcList({ status: 1 }).then((resp) => {
    if (resp) {
      listTypeInfo.value.menuList = resp.data.map((item) => {
        return {
          key: item.name,
          value: item.id,
        }
      })
    }
  })
}
const state = reactive({
  getOrderSequencePage,
  // 过滤相关配置
  filterInfo: {
    query: {
      sort: 'create_time desc',
      searchType: 'orderSequence',
    },
    list: [
      {
        type: 'button',
        label: '新增',
        show: proxy.$permission('orderSequence:add'),
        event: create,
      },
      {
        type: 'input',
        label: '名称/编码',
        value: 'keyword',
        event: search,
      },
      { type: 'button', label: '搜索', event: search },
    ],
  },
  // 表格相关
  tableInfo: {
    refresh: 1,
    initCurpage: 1,
    data: [],
    fieldList: [
      { label: '名称', value: 'name' },
      { label: '编码', value: 'code' },
      { label: '菜单', value: 'menuName' },
      { label: '前缀', value: 'prefix' },
      { label: '流水号长度', value: 'length' },
      { label: '创建人', value: 'createUserName' },
      { label: '创建时间', value: 'createTime' },
      { label: '备注', value: 'remark' },
    ],
    handle: {
      fixed: 'right',
      label: '操作',
      width: '50',
      btList: [
        {
          label: '修改',
          event: update,
          show: proxy.$permission('orderSequence:update'),
        },
      ],
    },
  },
  formTableInfo: {
    data: [
      {
        type: null,
        length: 1,
        originNumber: 0,
        isEnable: null,
        format: 'yyyyMMdd',
      },
    ],
    fieldList: [
      {
        label: '序列号规则',
        value: 'type',
        type: 'slot',
        code: 'order_rule',
        required: true,
      },
      {
        label: '时间格式',
        value: 'format',
        type: 'slot',
        code: 'date_format',
        required: true,
      },
      {
        label: '流水号长度',
        value: 'length',
        type: 'slot',
        required: true,
        width: 240,
      },
      {
        label: '重置周期',
        value: 'resetCycle',
        type: 'slot',
        code: 'validity_unit',
        required: true,
      },
      {
        label: '当前流水号',
        value: 'originNumber',
        type: 'slot',
        required: true,
        width: 240,
      },
      {
        label: '当前单号',
        value: 'currentOrder',
        type: 'slot',
        disabled: true,
        hidden: true,
      },
      {
        label: '是否启用',
        value: 'isEnable',
        type: 'slot',
        code: 'enabled_type',

        required: true,
      },
    ],
    handle: {
      fixed: 'right',
      label: '操作',
      width: '80',
      btList: [
        {
          label: '删除',
          event: del,
          show: true,
        },
      ],
    },
    rules: {
      originNumber: [
        {
          validator: originNumberValidate,
          trigger: 'blur',
        },
      ],
      length: [
        {
          validator: lengthValidate,
          trigger: 'blur',
        },
      ],
      type: [
        {
          validator: typeValidate,
          trigger: ['blur', 'change'],
        },
      ],
      format: [
        {
          validator: dateFormatValidate,
          trigger: 'blur',
        },
      ],
    },
  },
  formFilterInfo: {
    query: {},
    list: [
      {
        type: 'button',
        label: '添加',
        event: addTableItem,
      },
      {
        type: 'slot',
        label: '删除',
        value: 'deleteItem',
        event: batchDelete,
      },
    ],
  },
  // 表单相关
  formInfo: {
    ref: null,
    data: {
      length: '',
    },
    fieldList: [
      { label: '名称', value: 'name', type: 'input', required: true },
      { label: '编码', value: 'code', type: 'input', required: true },
      {
        label: '菜单',
        value: 'menuId',
        list: 'menuList',
        type: 'select',
        filterable: true,
        clearable: true,
        required: false,
      },
      { label: '前缀', value: 'prefix', type: 'input', required: true },
      {
        label: '流水号长度',
        value: 'length',
        type: 'input',
        placeholder: ' ',
        disabled: true,
        required: false,
      },
      {
        label: '备注',
        value: 'remark',
        type: 'textarea',
      },
    ],
    rules: {},
    labelWidth: '100px',
  },

  // 弹窗相关
  dialogInfo: {
    title: {
      create: '添加',
      update: '修改',
    },
    visible: false,
    type: '',
    width: '65%',
    btLoading: false,
    btList: [
      { label: '关闭', type: '', icon: '', event: close, show: true },
      {
        label: '保存',
        type: 'primary',
        icon: '',
        event: save,
        saveLoading: false,
        show: true,
      },
    ],
  },
  selectRow: '',
  errorClass: '',
})
function handleValidityUnit(row) {
  let format = row.format
  if (format === 'yyyyMMdd') {
    return ['0', '1', '2']
  }
  if (format === 'yyyyMM') {
    return ['1', '2']
  }
  if (format === 'yyyy') {
    return ['2']
  }
}
function change(str, row) {
  if (str === 'yyyyMMdd') {
    row.resetCycle = '0'
  }
  if (str === 'yyyyMM') {
    row.resetCycle = '1'
  }
  if (str === 'yyyy') {
    row.resetCycle = '2'
  }
}
// 获取列表
function getList() {
  state.tableInfo.refresh = Math.random()
}
// 初始化验证
function initRules() {
  const formInfo = state.formInfo
  formInfo.rules = proxy.$initRules(formInfo.fieldList)
}
// 搜索
function search() {
  // 重置分页
  state.tableInfo.initCurpage = Math.random()
  state.tableInfo.refresh = Math.random()
}
// 创建
function create() {
  state.formInfo.data = {}
  state.dialogInfo.type = 'create'
  state.dialogInfo.visible = true
  _.find(state.formTableInfo.fieldList, ['value', 'currentOrder']).hidden = true
}
// 编辑
function update(data) {
  state.dialogInfo.type = 'update'
  state.dialogInfo.visible = true
  // 显示信息
  state.formInfo.data = { ...data }
  state.formInfo.data['menuId'] = data.menuId == -2 ? '' : data.menuId
  getOrderSequenceDetail(data.id).then((res) => {
    if (res.success) {
      state.formTableInfo.data = res.data
      state.formTableInfo.data.map((item) => {
        if (item.isEnable) {
          state.formInfo.data.length = item.length
        }
      })
    }
  })
  _.find(state.formTableInfo.fieldList, [
    'value',
    'currentOrder',
  ]).hidden = false
}
function close() {
  state.dialogInfo.visible = false
  state.formInfo.data = {}
  state.formTableInfo.data = [
    { type: '', length: 1, originNumber: 0, isEnable: '' },
  ]
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    // 对表格获取到的数据做处理
    case 'tableCheck':
      state.selectRow = data
      break
  }
}
function handleDetails(params) {
  params.details.forEach((element) => {
    if (element.type == 1) {
      delete element.format
      delete element.resetCycle
    }
  })
}
function save() {
  const dialogInfo = state.dialogInfo
  const tableInfo = state.tableInfo
  let formValitator = false
  let tableValitator = false
  proxy.$refs.tableForm.validate((valid) => {
    if (valid) {
      tableValitator = true
    }
  })

  state.formInfo.ref.validate((valid) => {
    if (valid) {
      formValitator = true
      let api
      const params = state.formInfo.data
      params.details = state.formTableInfo.data
      handleDetails(params)
      const type = state.dialogInfo.type
      if (type === 'create') {
        api = createOrderSequencePage
      } else if (type === 'update') {
        api = updateOrderSequencePage
      } else {
        return
      }
      dialogInfo.btLoading = true
      api(params)
        .then((res) => {
          if (res.success) {
            dialogInfo.visible = false
            tableInfo.refresh = Math.random()
          }
          dialogInfo.btLoading = false
        })
        .catch((e) => {
          dialogInfo.btLoading = false
        })
    }
  })
  if (formValitator && tableValitator) {
    let api
    const params = state.formInfo.data
    params.details = state.formTableInfo.data
    handleDetails(params)
    const type = state.dialogInfo.type
    if (type === 'create') {
      api = createOrderSequencePage
    } else if (type === 'update') {
      api = updateOrderSequencePage
    } else {
      return
    }
    dialogInfo.btLoading = true
    api(params)
      .then((res) => {
        if (res.success) {
          dialogInfo.visible = false
          tableInfo.refresh = Math.random()
        }
        dialogInfo.btLoading = false
      })
      .catch((e) => {
        dialogInfo.btLoading = false
      })
  }
}
function addTableItem() {
  state.formTableInfo.data.push({
    type: '',
    length: 1,
    originNumber: 0,
    isEnable: '',
    format: 'yyyyMMdd',
  })
  handleIsEnable(state.formTableInfo.data)
}
function handleIsEnable(data) {
  proxy.$nextTick(() => {
    let arr = data.filter((element) => {
      return element.isEnable
    })
    if (arr[0] && arr[0].length) {
      state.formInfo.data['length'] = arr[0].length
    } else {
      state.formInfo.data['length'] = 1
    }
  })
}
function del(row, index) {
  if (state.formTableInfo.data.length === 1) {
    proxy.$message({
      type: 'warning',
      duration: '3500',
      message: '明细中至少保留一条数据',
      showClose: true,
    })
    return
  }
  state.formTableInfo.data.splice(index, 1)
}
function batchDelete() {
  state.formTableInfo.data = state.formTableInfo.data.filter(
    (row) => !state.selectRow.includes(row)
  )
}
function changeSwitch(value, index) {
  if (value) {
    state.formInfo.data.length = state.formTableInfo.data[index].length
    state.formTableInfo.data.forEach((item, itemIndex) => {
      if (index !== itemIndex) {
        item.isEnable = 0
      }
    })
    return
  }
  state.formInfo.data.length = ''
}
function originNumberValidate(rule, value, callback) {
  if (!value && value !== 0) {
    state.errorClass = 'error-form-item'
    callback('请输入当前流水号')
    return
  }
  state.errorClass = ''
  callback()
}
function lengthValidate(rule, value, callback) {
  if (!value) {
    state.errorClass = 'error-form-item'
    callback('请输入流水号长度')
    return
  }
  state.errorClass = ''
  callback()
}
function dateFormatValidate(rule, value, callback) {
  if (state.formTableInfo.type === 2 && !value) {
    callback('请选择时间格式')
    return
  }
  callback()
}
function typeValidate(rule, value, callback) {
  if (!value) {
    state.errorClass = 'error-form-item'
    callback('请选择规则')
    return
  }
  state.errorClass = ''
  callback()
}
function changeItemLength(row) {
  if (row.isEnable) {
    state.formInfo.data.length = row.length
  }
}
</script>

<style scoped lang="scss">
.sequence-table-form {
  :deep(.el-table) {
    max-height: 273px;
    overflow: auto;
    .el-form-item {
      margin-bottom: 0;
    }
    .error-form-item {
      .el-form-item {
        margin-bottom: 18px;
      }
    }
  }
}
</style>
